import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { app } from 'electron';

export class DatabaseManager {
  private static instance: DatabaseManager;
  private db: Database.Database | null = null;
  private dbPath: string;

  private constructor() {
    // 确保数据目录存在
    const userDataPath = app.getPath('userData');
    const dbDir = path.join(userDataPath, 'database');

    if (!fs.existsSync(dbDir)) {
      fs.mkdirSync(dbDir, { recursive: true });
    }

    this.dbPath = path.join(dbDir, 'app.db');
    this.init();
  }

  public static getInstance(): DatabaseManager {
    if (!DatabaseManager.instance) {
      DatabaseManager.instance = new DatabaseManager();
    }
    return DatabaseManager.instance;
  }

  private init(): void {
    try {
      this.db = new Database(this.dbPath);
      console.log('数据库连接成功!');

      // 开启WAL模式提高性能
      this.db.pragma('journal_mode = WAL');
      this.db.pragma('foreign_keys = ON');
    } catch (error) {
      console.error('数据库初始化失败:', error);
      this.db = null;
    }
  }

  public getDatabase(): Database.Database {
    if (!this.db) {
      throw new Error('数据库尚未初始化');
    }
    return this.db;
  }

  public closeDatabase(): void {
    if (this.db) {
      this.db.close();
      this.db = null;
      console.log('数据库连接已关闭');
    }
  }

  /**
   * 获取数据库文件路径
   * @returns 数据库文件的完整路径
   */
  public getDatabasePath(): string {
    return this.dbPath;
  }
}

export default DatabaseManager.getInstance();
